﻿using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using DTO;

namespace DAO
{
    public class QuanHuyenDAO : DataProvider
    {
        protected override object GetDataRowFromDataReader(OleDbDataReader dr)
        {
            QuanHuyenDTO quanHuyenDTO = new QuanHuyenDTO();
            if (!dr.IsDBNull(0))
            {
                quanHuyenDTO.MaQuanHuyen = dr.GetInt32(0);
            }
            
            if (!dr.IsDBNull(1))
            {
                quanHuyenDTO.TenQuanHuyen = dr.GetString(1);
            }

            return (object)quanHuyenDTO;
        }
        public List<QuanHuyenDTO> GetAllQuanHuyenDTO()
        {
            List<QuanHuyenDTO> lstQuanHuyenDTO = new List<QuanHuyenDTO>();
            try
            {
                string strSQL = @"SELECT *" +
                                @" FROM QUANHUYEN";

                using (OleDbDataReader dr = this.ExcuteReader(strSQL))
                {
                    while (dr.Read())
                    {
                        QuanHuyenDTO quanHuyenDTO = (QuanHuyenDTO)GetDataRowFromDataReader(dr);
                        lstQuanHuyenDTO.Add(quanHuyenDTO);
                    }
                }
            }
            catch (Exception ex)
            {
                lstQuanHuyenDTO = new List<QuanHuyenDTO>();
            }

            return lstQuanHuyenDTO;
        }
        public QuanHuyenDTO Search(int id)
        {
            QuanHuyenDTO quanHuyenDTO = null;
            try
            {
                string strSQL = @"SELECT *" +
                                @" FROM QUANHUYEN" +
                                @" WHERE MaQuanHuyen = " + id.ToString();

                using (OleDbDataReader dr = this.ExcuteReader(strSQL))
                {
                    if (dr.Read())
                    {
                        quanHuyenDTO = (QuanHuyenDTO)GetDataRowFromDataReader(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                quanHuyenDTO = null;
            }

            return quanHuyenDTO;
        }

        public int GetIdByName(string name)
        {
            int maQuanHuyen = -1;
            try
            {
                string strSQL = @"SELECT MaQuanHuyen" +
                                @" FROM QUANHUYEN" +
                                @" WHERE TenQuanHuyen = '" + name + "'";

                using (OleDbDataReader dr = this.ExcuteReader(strSQL))
                {
                    if (dr.Read())
                    {
                        maQuanHuyen = dr.GetInt32(0);
                    }
                }
            }
            catch (Exception ex)
            {
                maQuanHuyen = -1;
            }

            return maQuanHuyen;
        }
    }
}
